<template>
	<div>
	<el-card style="width: 100%; padding: 0px;">
		<el-form label-width="auto" :inline="true">
			<el-row :gutter="10">
				<el-col :span="20">
					<el-form-item label="请选择会员信息:" style="margin-bottom: 0px;width: 100%;">
						<el-select
							v-model="memPro.value"
							filterable
							clearable
							remote
							reserve-keyword
							placeholder="请输入会员ID、名称、手机号"
							:remote-method="memRemoteMethod"
							remote-show-suffix
							:loading="memPro.loading"
							style="width: 100%;"
							@change="memChange"
						  >
							<el-option
							  v-for="item in memPro.options"
							  :key="item.id"
							  :label="item.name+'    会员号:'+item.meId+'    联系电话:'+item.phone+'     会员等级:'+item.grade"
							  :value="item.meId"
							>
								  <span style="float: left;font-weight: bold;margin-right: 10px;">{{ item.name}}</span>
								  <span style="float: left;margin-right: 10px;">会员号:{{ item.meId}}</span>
								  <span style="float: left;color: red;">联系电话:{{ item.phone }}</span>
								  <span style="float: right;color: var(--el-text-color-secondary);font-size: 13px;">
									会员等级:{{ item.grade }}
								  </span>
							</el-option>
						  </el-select>
					</el-form-item>
				</el-col>
				<el-col :span="4">
					 <el-form-item style="margin-bottom: 0px;width: 100%;">
					  <el-button type="primary" style="width: 100%;"  @click="onAddMemInfo">新增会员信息</el-button>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
	</el-card>
	<memAddInfo ref="memAddInfoRef" :open="false" @saveOk="memSaveOk" />
	
	<el-row >
		<el-col :span="16">
			<el-card style="width: 100%;">
			    <template #header>
					<el-row style="height: 30px;">
						<el-col :span="12">
							 <span>产品</span>
						</el-col>
						<el-col :span="12" style="text-align: right;">
							<selectGoods lable="输入搜索:" @selectChange="goodsQuerySelectChange"/>
						</el-col>
					</el-row>
			    </template>
				<el-tabs v-model="tabPro.activeName" tab-position="left" class="demo-tabs" style="height: calc(100vh - 193px);" @tab-change="tabChange">
					<el-tab-pane  v-for="dict in bus_goods_type"
				          :key="dict.value"
				          :label="dict.label"
						  :name="dict.value"
				          :value="dict.value" >
						 <el-scrollbar style="height: calc(100vh - 193px);">
							 <el-row :gutter="10" v-for="item in tabPro.list" :key="item.id" @click="tabItemClick(item)">
								 <el-col :span="3">
									 <el-image style="width: 80px;height: 80px;" :src="imgPath(item.goodsImg)" fit="cover"></el-image>
								 </el-col>
								 <el-col :span="21">
									 <el-text size="large">{{item.goodsName}}</el-text><br /><br />
									 <el-text type="warning">库存{{item.inventory}}件</el-text><br />
									 <el-text type="danger">￥{{item.salePrice}}</el-text>
								 </el-col>
							 </el-row>
						 </el-scrollbar>
						 <el-empty v-if="tabPro.list.length==0" description="暂无数据" />
					</el-tab-pane>
				  </el-tabs>
			  </el-card>
			
			
		</el-col>
		<el-col :span="8">
			
			<el-card >
			    <template #header>
			      <div class="card-header" style="height: 30px;">
					<el-row>
						<el-col :span="12">
							<el-badge :value="countListSize()" class="item">
								<span>消费清单</span>
							</el-badge>
						</el-col>
						<el-col :span="12" style="text-align: right;">
							<el-popconfirm title="确定要清除当前的消费清单列表吗?" width="200px" @confirm="clearListItem">
							    <template #reference>
							      <el-text v-if="listPro.list.length>0" type="danger" style="cursor: pointer;">清除</el-text>
							    </template>
							</el-popconfirm>
						</el-col>
					</el-row>
			      </div>
			    </template>
				<div style="height: calc(100vh - 280px);">
					<el-row v-for="item in listPro.list" :key="item.id" style="margin-bottom: 5px;background-color: #f4f4f5;">
						<el-col :span="18">
							<div>
								{{item.goodsName}}
							</div>
							<div>
								<span style="color: red;font-weight: 100;font-size: 12px;">￥{{item.salePrice}}</span>
							</div>
						</el-col>
						<el-col :span="6" style="text-align: right;">
							<div>
								<el-button size="small" type="info" icon="minus" circle @click="setListDiff(item.id)" />
								<el-button size="small"  type="primary" icon="plus" circle @click="setListAdd(item.id)"/>
							</div>
							<div>
								<el-icon><CloseBold />{{item.count}}</el-icon>
							</div>
						</el-col>
					</el-row>
					<el-empty v-if="listPro.list.length==0" description="请选择产品" />
				</div>
			    
			    <template #footer>
					<div style="height: 50px; justify-content: center;">
						<el-row>
							<el-col :span="18">
								<p>总额：￥{{countListSum()}}</p>
							</el-col>
							<el-col :span="6">
								<el-button type="primary" style="width: 100px;height: 40px;" @click="setOrderList" :disabled="listPro.list.length==0">去结算</el-button>
							</el-col>
						</el-row>
					</div>
				</template>
			  </el-card>
			
		</el-col>
	</el-row>
	
	
	<el-drawer :title="drawerPro.title" :close-on-click-modal="false" :close-on-press-escape="false" size="35%" v-model="drawerPro.visible" :show-close="drawerPro.showClose" :destroy-on-close="true">
		<div id="set" v-if="!drawerPro.result">
			<div style="height: calc(100vh - 310px);">
				<el-scrollbar>
					<el-row v-for="item in orderPro.list" :key="item.id" style="margin-bottom: 5px;background-color: #f4f4f5;">
						<el-col :span="18">
							<div>
								{{item.goodsName}}
							</div>
							<div>
								<span style="color: red;font-weight: 100;font-size: 12px;">￥{{item.salePrice}}</span>
							</div>
						</el-col>
						<el-col :span="6" style="text-align: right;">
							<div style="padding: 10px;">
								<br/>
								<el-icon><CloseBold/>{{item.count}}</el-icon><span style="position: relative;top: -2px;">={{item.salePrice*item.count}}</span>
							</div>
						</el-col>
					</el-row>
				</el-scrollbar>
			</div>
			<el-row style="justify-content: center;">
				<el-col :span="5">
					数量：{{orderPro.total}}
				</el-col>
				<el-col :span="7">
					折扣：{{orderPro.discount==100?'无':orderPro.discount/100}}<span style="font-size: 9px;" v-if="memPro.value!=null&&memPro.discount<100">（会员折扣）</span>
				</el-col>
				<el-col :span="12" style="text-align: right;">
					金额：<span v-if="orderPro.amount!=orderPro.currentAmount" style="font-size: 12px;text-decoration:line-through;">￥{{orderPro.amount}}</span> <span style="color: red;font-weight: bold;">￥{{orderPro.currentAmount}}</span>
					<el-text style="margin-left: 10px;cursor: pointer;" type="primary" size="small" @click="changeCurrentAmount">整单改价</el-text>
				</el-col>
			</el-row>
			<el-divider content-position="center">销售信息</el-divider>
			<div>
				<el-form ref="submitRef" :model="form" label-position="right" :rules="rules" label-width="90px" >
					<el-form-item label="销售人员" prop="belUserId">
					  <el-select v-model="form.belUserId" placeholder="请选择销售人员">
						<el-option v-for="user in listUsers" :key="user.userId" :label="user.nickName" :value="user.userName" />
					  </el-select>
					</el-form-item>
					<el-form-item label="收款方式" prop="payWay">
					  <el-radio-group v-model="form.payWay" >
						<el-radio v-for="dict in bus_pay_way" name="payWay" :label="dict.value">{{dict.label}}</el-radio>
						<el-radio v-if="memPro.value!=null" name="payWay" label="99">储值卡<span style="color: red;font-size: 12px;">￥{{memPro.storedAmount}}</span></el-radio>
					  </el-radio-group>
					</el-form-item>
					 <el-form-item>
					  <el-button type="primary" @click="setOK">确认收款</el-button>
					</el-form-item>
				</el-form>
			</div>
		</div>
		<div id="ok" v-if="drawerPro.result" style="text-align: center;">
			<div class="no-print">
				 <el-row >
					<el-col :span="24">
					  <el-result
						icon="success"
						title="收款成功"
						:sub-title="'￥'+orderPro.currentAmount"
					  >
						<template #extra>
						  <el-button type="success" plain @click="goHome">回到首页</el-button>
						  <el-button type="primary" plain @click="startPrint">打印票据</el-button>
						</template>
					  </el-result>
					</el-col>
				</el-row>
			</div>
		</div>
	</el-drawer>
	
	
	<el-dialog
	    v-model="orderPro.dialogVisible"
		:close-on-click-modal="false"
		:destroy-on-close="true"
	    title="整单改价"
	    width="400"
	  >
	  
		<el-form :model="form" label-width="90">
		    <el-form-item label="总金额">
		      <el-input v-model="orderPro.changeCurrentAmount" readonly type="number" min="0"/>
		    </el-form-item>
			<el-form-item label="折扣率">
			  <el-input v-model="orderPro.changeDiscount" placeholder="例:8折,请写80" min="80" max="100" type="number"/>
			</el-form-item>
	    </el-form>
	    <template #footer>
	      <div class="dialog-footer">
	        <el-button @click="orderPro.dialogVisible = false">取消</el-button>
	        <el-button type="primary" @click="setCurrentAmount">确定</el-button>
	      </div>
	    </template>
	  </el-dialog>
	  
	 <diffStoredAmount ref="diffStoredAmountRef" @success="successStored"/>
	
	</div>
</template>

<script setup name="CashierInfo">
import { ref, watch } from "vue";
import { listGoodsInfo} from "@/api/crm/goodsInfo";
import { listUser } from "@/api/system/user";
import { localPay,print } from "@/api/crm/localOrder";

import { queryMemberInfo } from "@/api/crm/memberInfo";

import memAddInfo from "../memberInfo/addInfo.vue";

import selectGoods from '../goods/select.vue';

import diffStoredAmount from "../memberInfo/diffStoredAmount.vue";


const { proxy } = getCurrentInstance();
const { bus_goods_type,bus_pay_way } = proxy.useDict('bus_goods_type','bus_pay_way');

const diffStoredAmountRef = ref();

const listUsers = ref([]);


const memPro = reactive({
	value:null,
	options:[],
	loading:false,
	discount:100,
	storedAmount:0
})

const memAddInfoRef = ref();

const tabPro = reactive({
	activeName:"1",
	list:[]
})

const listPro = reactive({
	list:[]
})

const drawerPro = reactive({
	visible:false,
	showClose:true,
	title:"确定订单",
	result:false,
	orderId:null
})

const orderPro = reactive({
	list:[],
	amount:0,
	total:0,
	currentAmount:0,
	discount:100,
	dialogVisible:false,
	changeDiscount:100,
	changeCurrentAmount:0,
	memId:null
})

const form = reactive({
  belUserId: '',
  payWay: '1',
  orderInfo:{}
})

const rules = reactive( {
	    belUserId: [
			{ required: true, message: '请选择销售人员', trigger: ['blur','change'] },
		],
		payWay:[
			{ required: true, message: '请选择收款方式', trigger: 'change' },
		]
  })


watch(()=>orderPro.changeDiscount,(newvalue,oldvalue)=>{
	 orderPro.changeCurrentAmount =  orderPro.amount*(newvalue/100)
},{deep:true})



function loadListUsers(){
	listUser().then(rsp=>{
		listUsers.value = rsp.rows;
	})
}

function imgPath(relPath){
	return import.meta.env.VITE_APP_BASE_API+relPath
}

//*********************mem start
function onAddMemInfo(){
	console.log(memAddInfoRef.value.open)
	memAddInfoRef.value.openWin()
}

//会员添加成功后
function memSaveOk(data){
	memPro.value = data
	//触发查询接口
	memRemoteMethod(memPro.value)
}

function memRemoteMethod(query){
	 if (query) {
	    memPro.loading = true
		queryMemberInfo(query).then(rsp=>{
			memPro.loading = false
			memPro.options = rsp.rows
		})
		
	   
	  } else {
	    memPro.options = []
	  }
}

function memChange(params){
	
	for (var i = 0; i < memPro.options.length; i++) {
		if(memPro.options[i].meId === params){
			memPro.discount = memPro.options[i].discount;
			memPro.storedAmount = memPro.options[i].storedAmount;
			break;
		}
	}
}
//*********************mem end

//*********************tab start
function tabChange(typeValue){
	listGoodsInfo({goodsType:tabPro.activeName}).then(rsp=>{
		tabPro.list = rsp.rows
	})
}

function tabItemClick(item){
	//console.log(item.id,item.goodsName)
	setListItem(item)
}

function goodsQuerySelectChange(item){
	setListItem(item)
}

//***********************tab end

//***********************list start
function countListSize(){
	var size = 0;
	for (var i = 0; i < listPro.list.length; i++) {
		var item = listPro.list[i]
		size+=item.count;
	}
	return size;
}
function setListItem(goods){
	for (var i = 0; i < listPro.list.length; i++) {
		var item = listPro.list[i]
		if(item.id===goods.id){
			item.count ++;
			return;
		}
	}
	var newObj = Object.assign({},goods);
	newObj.count = 1;
	listPro.list.push(newObj)
}

function clearListItem(){
	listPro.list =[];
}

function countListSum(){
	var sum = 0;
	for (var i = 0; i < listPro.list.length; i++) {
		var item = listPro.list[i]
		sum+=(item.count*item.salePrice);
	}
	return sum
}

function setListAdd(id){
	for (var i = 0; i < listPro.list.length; i++) {
		var item = listPro.list[i]
		if(item.id===id){
			item.count ++;
			return;
		}
	}
}

function setListDiff(id){
	var x = -1;
	for (var i = 0; i < listPro.list.length; i++) {
		var item = listPro.list[i]
		if(item.id===id){
			item.count --;
			if(item.count==0){
				x = i;
			}
			break;
		}
	}
	if(x>-1){
		listPro.list.splice(x, 1);
	}
}

//***********************list end

//***********************order start
function setOrderList(){
	orderPro.list = listPro.list;
	orderPro.total = countListSize();
	orderPro.amount = countListSum();
	orderPro.discount = memPro.discount;
	
	if(orderPro.discount!=100){
		orderPro.currentAmount = (orderPro.amount*(orderPro.discount/100.0))
	}else{
		orderPro.currentAmount = orderPro.amount;
	}
	
	
	drawerPro.visible=true;
}
function changeCurrentAmount(){
	orderPro.dialogVisible =true;
	orderPro.changeDiscount = orderPro.discount;
	orderPro.changeCurrentAmount = orderPro.currentAmount;
}

function setCurrentAmount(){
	orderPro.dialogVisible = false;
	orderPro.discount = orderPro.changeDiscount;
	orderPro.currentAmount = orderPro.changeCurrentAmount;
}


//点击储值
function handleStored(row,type){
	diffStoredAmountRef.value.openWin(row,type)
}

//储值后回调
function successStored(value){
	memPro.storedAmount = value
}

//***********************order end

function setOK(){
	
	proxy.$refs["submitRef"].validate(valid => {
		if (valid) {
			
			var subData = Object.assign(orderPro,form);
			
			if(memPro.value!=undefined&&memPro.value!=null){
				subData.meId = memPro.value
			}
			//console.log(subData)
			
			if('99'==subData.payWay){
				//储值卡
				 if(memPro.storedAmount<subData.currentAmount){
					 proxy.$modal.confirm('储值卡余额不足是否充值?').then(()=>{
						handleStored({meId:memPro.value,storedAmount:memPro.storedAmount},'1')
					 }).catch(()=>{})
					 return false;
				 }
				 
			}
			
			localPay(subData).then(rsp=>{
				if(rsp.code==200){
					drawerPro.showClose = false;
					drawerPro.title="收款成功";
					drawerPro.result=true;
					drawerPro.orderId = rsp.data
				}else{
					proxy.$modal.notifyError(rsp.msg||'系统错误')
				}
				
			});
		}  
    })
	
	
}
function resetOk(){
	
	memPro.value = null;
	memPro.options = [];
	memPro.loading = false;
	memPro.discount = 100;
	memPro.storedAmount=0;
	
	drawerPro.showClose = true;
	drawerPro.title="确定订单";
	drawerPro.result=false;
	drawerPro.orderId=null;
	
	orderPro.list=[];
	orderPro.amount=0;
	orderPro.total=0;
	orderPro.currentAmount=0;
	orderPro.discount=100;
	orderPro.dialogVisible=false;
	orderPro.changeDiscount=100;
	orderPro.changeCurrentAmount=0;
	
	listPro.list = [];
	
	tabChange();
}

function goHome(){
	drawerPro.visible=false;
	resetOk();
}

function startPrint(){
	print(drawerPro.orderId).then(rsp=>{
		if(rsp.code!=200){
			proxy.$modal.notifyError(rsp.msg||'打印机处理异常，请检查打印机是否已开启并状态正常');
		}else{
			proxy.$modal.notifySuccess('发送打印机成功！')
		}
	})
}



loadListUsers();
tabChange();

</script>

<style>
	.el-drawer__header{
		margin-bottom: 2px;
	}
	.el-card__body{
		padding: 2px !important;
	}
</style>